package com.zwmuzhi.springcloud.controller;

import com.zwmuzhi.springcloud.entities.CommonResult;
import com.zwmuzhi.springcloud.entities.Payment;
import com.zwmuzhi.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <h3>cloudLearn</h3>
 * <p>paymentController</p>
 *
 * @author : zwmuzhi
 * @date : 2020-11-05 16:59
 **/
@Slf4j
@RestController
@RequestMapping("payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 创建
     * @param payment
     * @return
     */
    @PostMapping("")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("create payment={}",payment);

        if (result < 0 ){
            log.info("payment create fail");
            return new CommonResult(411,"创建失败");
        }

        return new CommonResult(200,"创建成功,serverPort: {} "+serverPort);
    };

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("getPaymentById id={}",id);
        if (paymentById == null){
            return new CommonResult(412,"查询失败");
        }
        log.info("getPaymentById success payment={}",paymentById);
        return new CommonResult(200,"查询成功,serverPort: {} "+serverPort,paymentById);
    };

    @GetMapping("discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        services.forEach( element -> {
            log.info("element data:{}",element);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(instance -> {
            log.info("instance data:{}",instance);
            log.info("getHost:{}",instance.getHost());
            log.info("getInstanceId:{}",instance.getInstanceId());
            log.info("getMetadata:{}",instance.getMetadata());
            log.info("getPort:{}",instance.getPort());
            log.info("getScheme:{}",instance.getScheme());
            log.info("getServiceId:{}",instance.getServiceId());
            log.info("getUri:{}",instance.getUri());
        });

        return this.discoveryClient;
    }

}
